package cn.tedu.egarticle1.controller;

import cn.tedu.egarticle1.base.response.JsonResult;
import cn.tedu.egarticle1.base.response.StatusCode;
import cn.tedu.egarticle1.mapper.UserMapper;
import cn.tedu.egarticle1.pojo.dto.UserArticleDTO;
import cn.tedu.egarticle1.pojo.dto.UserLoginDTO;
import cn.tedu.egarticle1.pojo.entity.Article;
import cn.tedu.egarticle1.pojo.vo.ArticleVO;
import cn.tedu.egarticle1.pojo.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;


@Api(tags="用户模块")
@Slf4j
@Validated
@RestController
@RequestMapping("/v1/users/")

public class UserController {
    @Autowired
    private UserMapper userMapper;
    @ApiOperation("登录模块")
    @PostMapping("login")
    public JsonResult login(@RequestBody UserLoginDTO userLoginDTO, @ApiIgnore HttpSession session){
        String username=userLoginDTO.getUsername();
        String password=userLoginDTO.getPassword();
        log.debug("userLoginDTO="+userLoginDTO);
        UserVO userVO =  userMapper.selectUser(username, password);

        if(userVO==null){
            return new JsonResult(StatusCode.USERNAME_PASSWORD_ERROR);
        }
        session.setAttribute("user",userVO);
        return JsonResult.ok();
    }
    @ApiOperation("文章模块")
    @PostMapping("article")
    public JsonResult article(@RequestBody @Validated UserArticleDTO userArticleDTO, @ApiIgnore HttpSession session){
        log.debug("userArticleDTO="+userArticleDTO);
        UserVO userVO = (UserVO) session.getAttribute("user");
        if(userVO==null){
            return new JsonResult(StatusCode.NOT_LOGIN);
        }
        Article article = new Article();
        BeanUtils.copyProperties(userArticleDTO,article);
        article.setUserId(userVO.getId());
        userMapper.insert(article);
        return JsonResult.ok();

    }
    @ApiOperation("查询文章模块")
    @ApiImplicitParam(name = "id",value = "文章id",required = true,dataType = "int")
    @GetMapping("selectByArticle")
    public JsonResult selectByArticle(@Range(min=1,max=100,message="文章id在1-100之间")@RequestParam Integer id){
        ArticleVO articleVO= userMapper.selectByArticleId(id);
        return JsonResult.ok(articleVO);

    }

}
